import globals
import yaml
from msg import Message
import configfile
import GetDataFromAuthServer

def check_failure_message (msg) :

    flag = True
    try :
        globals.globalFailureMessageListLock.acquire()
        for m in globals.globalFailureMessageList :
            if msg.broadcastSource == m.broadcastSource and msg.data == m.data :
                flag = False
                break
    finally :
        globals.globalFailureMessageListLock.release()
    return flag


def handle_failure (mp, msg) :

    try :
        globals.globalFailureMessageListLock.acquire()
        globals.globalFailureMessageList.append(msg)
    finally :
        globals.globalFailureMessageListLock.release()

    source = msg.broadcastSource
    failureList = msg.data
    print "Source : " + source,
    print " failureList : ",
    print failureList

    try :
        for item in failureList :
            #print "hintmap : ",
            #print mp.hintMap
            #print "Called unlink"
            if msg.broadcastSource ==  mp.thisName :
                GetDataFromAuthServer.unlink_from_auth_server(source, item)
            #globals.globalConfiguration = yaml.load(GetDataFromAuthServer.get_config_from_auth_server(mp.thisName))

            configfile.remove_edge(source, item)

            #for item in globals.globalConfiguration :
            #    item['group'] = configfile.comGraph[item['name']]

            #print configfile.remove_edge(source, item)
            #del mp.hintMap[item]
    except KeyError :
        #print "KeyError"
        pass
    #mapS = mp.ConfigurationMap[mp.thisName]

    listDest = []
    for item in configfile.get_node_neighbors(mp.thisName) :
        if not item == mp.thisName :
            if not item == msg.src:
                if not item in failureList :
                    listDest.append(item)

    msg.src = mp.thisName

    #print "listDest : ",
    #print listDest

    msg.dest = listDest
    msg.destArray= listDest

    mp.send(msg)
    return
